package com.example.filter;

import com.alibaba.fastjson2.JSON;
import com.example.contanxt.Context;
import com.example.module.User;
import com.example.utils.Fastjson2ConverterUtils;
import com.example.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader(Context.HEAD_TOKEN);
        if(!StringUtils.hasLength(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        User user;
        try {
            //解析token
            String userId = JwtUtils.jwtToUserId(token);
            user = Fastjson2ConverterUtils.fromJson(redisTemplate.opsForValue().get(userId),User.class);
        }catch (Exception e){
            log.error("token异常",e);
            throw new RuntimeException("token非法");
        }
        //设置信息到上下文

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user,null,null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行
        filterChain.doFilter(request,response);
    }
}
